<template>
  <div class="app-container">
    <el-upload
      class="avatar-uploader"
      action=""
      :http-request="upload"
      :before-upload="beforeUpload"
      :show-file-list="false"
    >
      <img v-if="url" :src="url" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>

  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
import uuid from 'uuid-v4'
export default {
  name: 'ImageUpload',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  /*   data() {
    return {
      // imageUrl: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      imageUrl: ''
    }
  }, */
  created() {
    this.cos = new COS({
      SecretId: 'AKIDvdOzNe2P00qTvGS6IMKC1sc8NQTVuH5i',
      SecretKey: 'DsIWgjrBNOYgMZbU7rgJBXnJgpmX5oTa'
    })
  },
  methods: {
    upload({ file }) {
      console.log('自定义上传', file)
      this.cos.putObject({
        Bucket: 'hr-88-1256173530', /* 必须 */
        Region: 'ap-shanghai', /* 存储桶所在地域，必须字段 */
        Key: uuid() + '.' + file.name.split('.')[1], /* 必须,上传的文件的名字 */
        StorageClass: 'STANDARD',
        Body: file // 上传文件对象
      }, (err, data) => {
        if (err) return console.log(err)
        console.log('上传成功', data.Location)
        // this.imageUrl = 'https://' + data.Location
        // 通知父组件 并改地址为 对象存储中图片的地址
        this.$emit('update:url', 'https://' + data.Location)
      })
    },
    beforeUpload(file) {
    //   console.log(file, '上传之前校验')
    // 对上传之前的文件进行判断做处理
      if (!['image/jpeg', 'image/png'].includes(file.type)) {
        this.$message.error('图片格式只能为png或jpg')
        return false
      }
      if (file.size / 1024 / 1024 > 1) {
        this.$message.error('图片大小不能超过1M')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  ::v-deep {
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .el-upload:hover {
      border-color: #409EFF;
    }
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
